<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Document</title>
	</head>
	<body>
		<div id="messages" class="top-container">
			<h4>对话：</h4>
		</div>
		<div class="middle-container">
			<input
				id="user-input"
				class="input-box"
				type="textarea"
				onkeydown="handleKeyPress(event)"
			/>
			<button>发送</button>
		</div>
	</body>

	<script>
		const socket = new WebSocket('ws://localhost:8000/ws/chat/')
		socket.onmessage = (e) =>
			(document.getElementById('messages').innerHTML += e.data + '<br>')
		document.querySelector('button').onclick = () => {
			let txt = document.getElementById('user-input').value
			if (txt) {
				document.getElementById('messages').innerHTML +=
					'客户端：' + txt + '<br>'
				socket.send(txt)
				document.getElementById('user-input').value = null
			}
		}

		function handleKeyPress(event) {
			if (event.key === 'Enter') {
				document.querySelector('button').onclick()
			}
		}
	</script>

	<style>
		.top-container {
			background-color: aqua;
			height: 400px;
		}

		.middle-container {
			margin-top: 20px;
			height: 50px;
			background-color: antiquewhite;
			display: flex;
			justify-content: center;
			text-align: center;
		}

		.input-box {
			width: 50%;
			border-radius: 5px;
		}
	</style>
</html>
